import 'dart:async';
import 'dart:io';

import 'package:file_transfer/model/simple_model.dart';
import 'package:file_transfer/route/simple_route.dart';
import 'package:flutter/material.dart';
import 'package:file_transfer/manager/webrtc_manager.dart';
import 'package:provider/provider.dart';
import 'package:receive_sharing_intent/receive_sharing_intent.dart';

class Application extends StatefulWidget {
  final Widget child;
  const Application({super.key,required this.child});

  @override
  State<Application> createState() => _ApplicationState();
}

class _ApplicationState extends State<Application> with WidgetsBindingObserver{

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  static const String _server = "ws://file.suxii.cn";
  // static const String _server = "ws://192.168.51.13:8900";

  _receiveSharingIntent(BuildContext context) async{
    // 已经有实例后调用
    ReceiveSharingIntent.instance.getMediaStream().listen((event) {
      _handlerShare(event);
    });

    // 第一次启动调用
    ReceiveSharingIntent.instance.getInitialMedia().then((value) {
      _handlerShare(value);
    });

  }

  _handlerShare(List<SharedMediaFile> value){
    if(value.isEmpty){
      return;
    }
    debugPrint("分享文件...");
    final simpleModel = context.read<SimpleModel>();

    debugPrint("文件类型：${value.first.type}");
    debugPrint("文件内容：${value.first.toMap()}");
    SimpleRoute.instance().toReceiveSharingPage(context);
    final type = value.first.type;
    if(!(type == SharedMediaType.text || type == SharedMediaType.url)) {
      simpleModel.isShareFile = true;
      value.forEach(((f) => simpleModel.addShareFile(File(f.path))));
    }else{
      simpleModel.isShareFile = false;
      simpleModel.shareText = value.first.path;
    }
    ReceiveSharingIntent.instance.reset();
  }


  WebrtcManager? _webrtcManager;
  _start(BuildContext context) {
    _webrtcManager = WebrtcManager.instance(context);
    _webrtcManager!.connectServer(_server);
    // _webrtcManager!.connectServer("ws://file.suxii.cn");
    _receiveSharingIntent(context);
  }

  @override
  Widget build(BuildContext context) {
    // 自定义生命周期
    _start(context);
    return widget.child;
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
        debugPrint('应用进入前台');
        if (!_webrtcManager!.simpleModel!.wsConnectState){
          _webrtcManager!.connectServer(_server);
        }
        // 类似于 onStart()
        break;
      case AppLifecycleState.inactive:
        debugPrint('应用变为非活跃状态');
        break;
      case AppLifecycleState.paused:
        debugPrint('应用进入后台');
        // 类似于 onStop()
        break;
      case AppLifecycleState.detached:
        _webrtcManager?.close();
        debugPrint('应用与系统分离');
        break;
      case AppLifecycleState.hidden:
        debugPrint('应用hidden');
    }
  }


  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _webrtcManager?.close();
    super.dispose();
  }

}
